import React, {useEffect, useRef, useState} from "react";
import {useModel} from "@@/exports";
import {message, Spin, Switch, TreeDataNode, TreeSelect} from "antd";
import {ActionType, PageContainer, ProColumns, ProTable} from "@ant-design/pro-components";
import {getGroups, setGroupPower} from "@/services/group/group";
import {getDepartmentMembers, getDepartments} from "@/services/department/department";
import moment from 'moment';

const Group = () => {
  const [loading, setLoading] = useState(false);
  const {initialState, setInitialState} = useModel('@@initialState');
  const actionRef = useRef<ActionType>();
  const [currentIndex, setCurrentIndex] = useState(0)
  const [size, setSize] = useState(10)

  const [departments, setDepartments] = useState([])
  const [sales, setSales] = useState([])
  const getDepartmentList = async () => {
    const res = await getDepartments()
    if (res.code !== 1) {
      message.error('获取部门列表失败,' + res.msg)
      return
    }
    console.log('all departments', res.data)
    const buildTreeNodes = async (departments) => {
      const findChildren = (parent) => {
        return departments.filter(department => department.parentId === parent.wxDid)
          .map(department => {
            const item: TreeDataNode = {
              key: department.wxDid,
              value: department.wxDid,
              title: department.name,
              parentId: department.parentId,
              children: findChildren(department)
            }
            return item
          })
      };
      const rootNodes = departments.filter(department => department.parentId === 0)
        .map(department => {
          const item: TreeDataNode = {
            key: department.wxDid,
            value: department.wxDid,
            title: department.name,
            parentId: department.parentId,
            children: findChildren(department)
          }
          return item
        });
      return rootNodes;
    }
    const departmentSelectData = await buildTreeNodes(res.data);
    setDepartments(departmentSelectData)
  }
  const getSalesList = async () => {
    const res = await getDepartmentMembers({
      page: 1,
      size: 9999,
    })
    if (res.code !== 1) {
      message.error('获取销售列表失败,' + res.msg)
      return
    }
    console.log('all sales', res)
    const sales = []
    res.data.records.forEach(sale => {
      sales.push({
        title: sale.name,
        label: sale.name,
        value: sale.wxUid
      })
    })
    setSales(sales)
  }

  useEffect(() => {
    getDepartmentList()
    getSalesList()
  }, []);

  const columns: ProColumns<CUSTOMER.Customer>[] = [
    {
      title: '名称',
      dataIndex: 'groupName',
      key: 'groupName',
    },
    {
      title: '归属门店',
      dataIndex: 'departmentName',
      key: 'departmentName',
      hideInSearch: true,
    },
    {
      title: '归属门店',
      dataIndex: 'wxDid',
      key: 'wxDid',
      hideInTable: true,
      renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
        // 当表单项被渲染时，使用TreeSelect组件
        return <TreeSelect
          {...rest}
          treeData={departments}
          placeholder="请选择门店"
          treeDefaultExpandAll
        />;
      },
    }, {
    //   title: '归属门店',
    //   dataIndex: 'departmentName',
    //   key: 'departmentName',
    //   hideInSearch: true,
    //   renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
    //     // 当表单项被渲染时，使用TreeSelect组件
    //     return <TreeSelect
    //       {...rest}
    //       treeData={departments}
    //       placeholder="请选择部门"
    //       treeDefaultExpandAll
    //     />;
    //   },
    // },
    // {
    //   title: '归属微信群',
    //   dataIndex: 'wechatGroupName',
    //   key: 'wechatGroupName',
    //   hideInSearch: true
    // },
    // {
      title: '绑定销售',
      key: 'salesName',
      dataIndex: 'salesName',
      hideInSearch: true,
    }, {
      title: '绑定销售',
      key: 'salesWxUid',
      dataIndex: 'salesWxUid',
      hideInTable: true,
      renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
        // 当表单项被渲染时，使用TreeSelect组件
        return <TreeSelect
          {...rest}
          treeData={sales}
          placeholder="请选择销售"
          treeDefaultExpandAll
        />;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      valueType: 'dateRange',
      hideInTable: true,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
        // 当表单项被渲染时，使用RangePicker组件
        if (type === 'form') {
          return <RangePicker showTime={{format: 'HH:mm:ss'}} format="YYYY-MM-DD HH:mm:ss" {...rest} />;
        }
        // 使用默认渲染逻辑
        return defaultRender(_);
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      hideInSearch: true,
      render: (text, record) => {
        return text? moment(text).format('YYYY-MM-DD HH:mm:ss') : ' - '
      }
    }, {
      title: '播放权限',
      dataIndex: 'audioPower',
      key: 'audioPower',
      hideInSearch: true,
      render: (text, record) => {
        return <Switch checked={record.audioPower} onChange={async (checked: boolean, event: Event) => {
          console.log('switch', record)
          setLoading(true)
          const params = {
            wxGid: record.wxGid,
            audioPower: !record.audioPower ? 1 : 0
          }
          const res = await setGroupPower(params)
          setLoading(false)

          if (res.code === 1) {
            actionRef.current?.reload()
            message.success('操作成功')
          } else {
            message.error('操作失败')
          }
        }}/>
      }
    },
    // {
    //   title: '操作',
    //   valueType: 'option',
    //   render: (text, record, _, action) => [
        // <a key="editable" onClick={async () => {
        //   setLoading(true)
        //   const res = await getCustomerDetail({
        //     wxUid: record.unionid
        //   })
        //   console.log('get customer detail', res)
        //   setDetail(res.data)
        //   setRecord(record)
        //   setModal(true)
        // }}>
        //   查看用户详情
        // </a>,
        // <a onClick={async () => {
        //   setRecord(record)
        //   setMemoModal(true)
        // }}>维护备注</a>
      // ],
    // },
  ]

  return (
    <PageContainer>
      <Spin spinning={loading} tip="加载中...">
        <ProTable
          rowKey={'key'}
          columns={columns}
          actionRef={actionRef}
          cardBordered
          request={async (params, sort, filter) => {
            const reqParams = {
              ...params,
              page: currentIndex,
              size: size
            }
            // if (reqParams.registerTime) {
            //   reqParams.registerTimeStart = String(params.registerTime).split(',')[0]
            //   reqParams.registerTimeEnd = String(params.registerTime).split(',')[1]
            // }
            // if (reqParams.addSalesTime) {
            //   reqParams.addSalesTimeStart = String(params.addSalesTime).split(',')[0]
            //   reqParams.addSalesTimeEnd = String(params.addSalesTime).split(',')[1]
            // }
            const res = await getGroups(reqParams)
            console.log('get group list', res)
            return {
              data: res.data.records,
              // success 请返回 true，
              // 不然 table 会停止解析数据，即使有数据
              success: true,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: res.data.total,
            };
          }}
          pagination={{
            pageSize: size,
            onChange: (page) => setCurrentIndex(page),
          }}
          dateFormatter="string"
          // toolBarRender={() => shouldShowModifyRecord(initialState.currentUser.roles) && ([
          //   <Button
          //     key="button"
          //     onClick={() => {
          //       if (selectedRowKeys.length === 0) {
          //         message.error('请先选择用户')
          //         return
          //       }
          //       setMoveModal(true)
          //     }}
          //     type="primary"
          //   >
          //     批量转移顾客
          //   </Button>,
          // ])}
        />
      </Spin>
    </PageContainer>
  );
}

export default Group;
